// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

use std::cell::Cell;
use serde::{Deserialize, Serialize};
use rusqlite::{params, Connection, Error, Result as SqlResult};
use tauri::{command, AppHandle, Manager, Result as TauriResult};

#[derive(Debug, Serialize, Deserialize)]
struct Todo {
    id: i32,
    text: String,
    completed: bool,
}

fn rusqlite_to_tauri_error(e: rusqlite::Error) -> tauri::Error {
    anyhow::Error::from(e).into()
}

#[command]
fn get_todos() -> TauriResult<Vec<Todo>> {
    let conn = Connection::open("todos.db").map_err(rusqlite_to_tauri_error)?;
    let mut stmt = conn.prepare("SELECT id, text, completed FROM todos").map_err(rusqlite_to_tauri_error)?;
    let todo_iter = stmt.query_map([], |row| {
        Ok(Todo {
            id: row.get(0)?,
            text: row.get(1)?,
            completed: row.get(2)?,
        })
    }).map_err(rusqlite_to_tauri_error)?;

    let mut todos = Vec::new();
    for todo in todo_iter {
        todos.push(todo.map_err(rusqlite_to_tauri_error)?);
    }
    Ok(todos)
}

#[command]
fn add_todo(text: String) -> TauriResult<()> {
    let conn = Connection::open("todos.db").map_err(rusqlite_to_tauri_error)?;
    conn.execute(
        "INSERT INTO todos (text, completed) VALUES (?1, ?2)",
        params![text, false],
    ).map_err(rusqlite_to_tauri_error)?;
    Ok(())
}

#[command]
fn toggle_todo(id: i32) -> TauriResult<()> {
    let conn = Connection::open("todos.db").map_err(rusqlite_to_tauri_error)?;
    let mut stmt = conn.prepare("SELECT completed FROM todos WHERE id = ?1").map_err(rusqlite_to_tauri_error)?;
    let completed: bool = stmt.query_row([id], |row| row.get(0)).map_err(rusqlite_to_tauri_error)?;
    conn.execute(
        "UPDATE todos SET completed = ?1 WHERE id = ?2",
        params![!completed, id],
    ).map_err(rusqlite_to_tauri_error)?;
    Ok(())
}

#[command]
fn delete_todo(id: i32) -> TauriResult<()> {
    let conn = Connection::open("todos.db").map_err(rusqlite_to_tauri_error)?;
    conn.execute("DELETE FROM todos WHERE id = ?1", [id]).map_err(rusqlite_to_tauri_error)?;
    Ok(())
}
#[command]
fn test_cell(param:i32)->TauriResult<i32>{
    let cell = Cell::new(5);
    let value = cell.get();
    println!("Initial value: {}", value);
    cell.set(param);
    let new_value = cell.get();
    println!("Updated value: {}", new_value);
    Ok(value)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![
            greet,
            get_todos,
            add_todo,
            toggle_todo,
            delete_todo,
            test_cell
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
